package com.lglin.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lglin.bean.product.entity.Category;
import com.lglin.bean.product.entity.Product;
import com.lglin.bean.product.vo.CartVo;
import com.lglin.bean.product.vo.CategoryVo;
import com.lglin.bean.product.vo.ProductVo;
import com.lglin.bean.user.entity.User;
import com.lglin.common.bean.Review;
import com.lglin.common.constant.Constant;
import com.lglin.common.utils.bean.BeanCopyUtil;
import com.lglin.common.utils.reponse.ResultBean;
import com.lglin.common.utils.reponse.ResultEnum;
import com.lglin.service.product.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("category")
    public ResultBean category(@RequestParam("key") String key) {
        System.out.println(key);
        List<Category> categories = productService.getCategory();
        return buildCategoryVo(categories, key);
    }

    public ResultBean<List<CategoryVo>> buildCategoryVo(List<Category> categories, String key) {
        if (categories != null && !categories.isEmpty()) {
            List<CategoryVo> categoryVos = new ArrayList<>(categories.size());
            categories.forEach(category -> {
                CategoryVo categoryVo = BeanCopyUtil.copy(category, CategoryVo.class);
                categoryVo.setCount(productService.getProductCountBycId(category.getId(), key));
                categoryVos.add(categoryVo);
            });
            return ResultBean.success().data(categoryVos);
        } else {
            return ResultBean.fail().setResultEnum(ResultEnum.Not_Data);
        }
    }

    @PostMapping("select")
    public ResultBean select(@RequestBody String data) {
        List<Product> products = productService.selectProducts(data);
        if (products != null && !products.isEmpty()) {
            return buildProductListVo(products);
        } else {
            return ResultBean.fail().setResultEnum(ResultEnum.Not_Data);
        }
    }

    public ResultBean<List<Product>> buildProductListVo(List<Product> products) {
        List<ProductVo> productVos = new ArrayList<>(products.size());
        products.forEach(product -> {
            ProductVo productVo = BeanCopyUtil.copy(product, ProductVo.class);
            List<Integer> stars = productService.getAllStarById(product.getId());
            int reviewsCount = stars.size();
            calcAverageStar(productVo, reviewsCount, stars);
            productVos.add(productVo);
        });
        PageInfo pageInfo = new PageInfo<>(products);
        pageInfo.setList(productVos);
        return ResultBean.success().data(pageInfo);
    }

    @GetMapping("id/{id}")
    public ResultBean selectOneById(@PathVariable int id, @RequestParam int pageNum) {
        Product product = productService.selectOneById(id);
        if (product == null) {
            return ResultBean.fail().setResultEnum(ResultEnum.Not_Data);
        }
        return buildProductVo(product, pageNum);
    }

    public ResultBean<ProductVo> buildProductVo(Product product, int pageNum) {
        ProductVo productVo = BeanCopyUtil.copy(product, ProductVo.class);
        PageHelper.startPage(pageNum, Constant.PageSize);
        List<Review> reviews = productService.getReviewsById(product.getId());
        for(Review review:reviews){
            User user= BeanCopyUtil.copy(review.getUser(),User.class);
            user.setImg(Constant.IMG_URl+user.getImg());
            review.setUser(user);
        }
        PageInfo<Review> pageInfo = new PageInfo<>(reviews);
        productVo.setReviews(pageInfo);
        List<Integer> stars = productService.getAllStarById(product.getId());
        productVo.setReviewCount(stars.size());
        calcAverageStar(productVo, (int) pageInfo.getTotal(), stars);
        return ResultBean.success().data(productVo);
    }

    /**
     * 计算平均星星
     *
     * @param productVo
     * @param reviewsCount
     * @param stars
     */
    private void calcAverageStar(ProductVo productVo, int reviewsCount, List<Integer> stars) {
        int starNum = 0;
        for (int star : stars) {
            starNum += star;
        }
        if (starNum == 0 || reviewsCount == 0) {
            productVo.setAverageStar(5);
        } else {
            productVo.setAverageStar(Math.round(starNum / reviewsCount));
        }
    }

    @PostMapping("cart")
    public ResultBean cart(@RequestBody String data) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String cart = jsonObject.getString("cart");
            cart = cart.substring(0, cart.length() - 1);
            String[] arrItem = cart.split(",");
            List<Integer> listPid = new ArrayList<>();
            Map<Integer, Integer> map = new HashMap<>();
            for (String s : arrItem) {
                String[] strArr = s.split("-");
                listPid.add(Integer.valueOf(strArr[0]));
                map.put(Integer.valueOf(strArr[0]), Integer.valueOf(strArr[1]));
            }
            List<Product> products = productService.selectProductsByIds(listPid);
            return buildCartVo(products, map);
        } catch (Exception e) {
            return ResultBean.fail().msg("数据解析异常");
        }
    }

    private ResultBean buildCartVo(List<Product> products, Map<Integer, Integer> map) {
        CartVo cartVo = new CartVo();
        cartVo.setProductNum(products.size());
        int subtotal = 0;
        int total;
        for (Product product : products) {
            product.setNum(map.get(product.getId()));
            subtotal += product.getNewPrice() * product.getNum();
        }
        cartVo.setSubtotal(subtotal);
        if (subtotal < 100) {
            cartVo.setEmsPrice(20);
            total = subtotal + 20;
        } else {
            total = subtotal;
        }
        cartVo.setProducts(products);
        cartVo.setTotal(total);
        return ResultBean.success().data(cartVo);
    }

    @GetMapping("recom/{num}")
    public ResultBean recomProduct(@PathVariable int num) {
        List<Map<String, Object>> list = productService.recomProduct(num);
        return ResultBean.success().data(list);
    }
}
